package com.css.devops.monitor;

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;

public class JenkinsViewManager2 {

    // 连接 Jenkins 需要设置的信息
    static final String JENKINS_URL = "http://192.168.94.1:18080";
    static final String JENKINS_USERNAME = "admin";
    static final String JENKINS_PASSWORD = "p@ssw0rd";

    /**
     * 使用 HTTP 请求将 Job 从 View 中移除
     */
    public static void removeJobFromView(String viewName, String jobName) {
        try {
            // 构造 API URL
            String urlStr = JENKINS_URL + "/view/" + viewName + "/removeJobFromView";
            URL url = new URL(urlStr);

            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);

            // 设置授权头
            String auth = JENKINS_USERNAME + ":" + JENKINS_PASSWORD;
            String encodedAuth = Base64.getEncoder().encodeToString(auth.getBytes());
            connection.setRequestProperty("Authorization", "Basic " + encodedAuth);

            // 构建请求体
            String postData = "name=" + jobName;
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = postData.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            // 发送请求并获取响应
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                System.out.println("Job '" + jobName + "' has been removed from view '" + viewName + "'");
            } else {
                System.out.println("Failed to remove job. Response Code: " + responseCode);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        try {
            // 目标 View 和 Job 名称
            String viewName = "test-view";
            String jobName = "test-job";

            // 从 View 中移除 Job
            removeJobFromView(viewName, jobName);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

